package com.base.utils;

import java.security.MessageDigest;
import java.util.Date;

public class MD5Utils {
	/**
	 * 获得当前系统时间并加密获得一串MD5密文，为了防止由于取得时间重复而获得相同密文所以选择加锁
	 * @return
	 */
	public static synchronized String MD5(){
		MessageDigest messageDigest=null;
		String source=Long.toString(new Date().getTime());
		try{
			messageDigest=MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(source.getBytes());;
		}catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		byte[] byteArray=messageDigest.digest();
		StringBuffer md5StrBuff=new StringBuffer();
		for(int i=0;i<byteArray.length;i++){
			if(Integer.toHexString(0xFF & byteArray[i]).length()==1){
				md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
			}else{
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		}
		return md5StrBuff.toString();
	}
	
	/**
	 * 对源数据进行MD5加密
	 * @param source
	 * @return
	 */
	public static String MD5(String source){
		MessageDigest messageDigest=null;
		try{
			messageDigest=MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(source.getBytes());;
		}catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		byte[] byteArray=messageDigest.digest();
		StringBuffer md5StrBuff=new StringBuffer();
		for(int i=0;i<byteArray.length;i++){
			if(Integer.toHexString(0xFF & byteArray[i]).length()==1){
				md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
			}else{
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
			}
		}
		return md5StrBuff.toString();
	}
}
